package com.hmall.order.instener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.impl.OrderService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MQinsten {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ItemClient itemClient;

    /**
     * 监听死信交换机30分钟后的延时信息，判断是否已支付，未支付则恢复商品库存数据
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.queue"),
            exchange = @Exchange(name = "dl.topic",type = ExchangeTypes.TOPIC),
            key = "dl"
    ))
    public void listenOrderQueue(Long id) {
        Order order = orderService.getById(id);
        if (order != null) {
            Integer status = order.getStatus();
            if (status == 1) {
                //如果未支付，订单状态设置为5
                order.setStatus(5);
                orderService.updateById(order);
                //创建条件构造器
                LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
                //构造条件
                wrapper.eq(OrderDetail::getOrderId,order.getId());
                //查询具体订单详情信息
                OrderDetail orderDetail = orderDetailService.getOne(wrapper);
                //获取购买数量
                Integer num = orderDetail.getNum(); //todo 注意幂等判断，避免重复消息,代码待完善
                //恢复库存
                Long itemId = orderDetail.getItemId();
                Item item = itemClient.getById(itemId);
                item.setStock(item.getStock()+num);
                itemClient.recoverStock(item);
            }

        }
    }

}
